<?php
$root_permission    = null;

if ($act == "logout")
{
    Logout();
}
if($module=="index" && ($act=="login" || $act=='login2'))
{
    //login page
}
else
{
    if(checkAdminLogin()==false)
    {
        if($act!="login" && $act!="logout" && $act!="sitemap" && $act!="cronjob")
        {
            gpc_setSession("urlref",$_SERVER['REQUEST_URI']);
        }else
        {
            gpc_removeSession("urlref");
        }
        header("Location: ?module=index&opt=login");
        exit;
    }

    //check permission
    if(($idadmin=getIdAdmin())!=1)
    {
    	$sql_select        = "select per.cPermission from tblpermission as per JOIN tblaccount as acc ON
    					       per.iId=acc.iGroupId and acc.iAccountId='".$idadmin."'";

    	$result            = $dbsql->query_fetch($sql_select);
        $root_permission   = buildPermission($result['cPermission']);
        $act_per           = 'view';
        
        if(strpos($act,'add')!==false || strpos($act,'insert')!==false)
        {
            $act_per      = 'add';
        }
        else if(strpos($act,'edit')!==false || strpos($act,'update')!==false)
        {
            $act_per      = 'edit';
        }
        else if(strpos($act,'delete')!==false || strpos($act,'del')!==false)
        {
            $act_per      = 'del';
        }
        
        $peract           = $root_permission[$module][$act_per];
        if($module=="account" &&($act=="myaccount" || $idadmin==$_POST['id']))
        {
            //cho phep vao myaccount
            $peract=1;
        }
		if($peract==0 && $module!="index")
		{
            $url=(strpos($_SERVER['HTTP_REFERER'],"?module=")!==false)? $_SERVER['HTTP_REFERER'] : "?module=index";
			page_transfer("You has not permission this action",$url);
			exit();
		}
    }
    //set url go back:
    if($act=="index")
    {
        gpc_setSession("UrlBack",$_SERVER['REQUEST_URI']);
    }
}

function buildPermission($str)
{
    $permission     = array();
    $arr1           = explode("|",$str);
    foreach($arr1 as $i=>$per)
    {
        $arr2       = explode(":",$per);
        $name       = $arr2[0];
        $mod        = intval($arr2[1]);
        $mod_add    = $mod&1;
        $mod_edit   = $mod&2;
        $mod_del    = $mod&4;
        $mods       = array('view'=>$mod,'add'=>$mod_add,'edit'=>$mod_edit,'del'=>$mod_del);
        $permission[$name]=$mods;
    }
    return $permission;
}
?>